package com.gupao.p7store.common.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.gupao.p7store.common.utils.DictUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * desc:
 *
 * @ClassName: com.gupao.p7store.common.convert.ExcelListConverter
 * @author: dengbicheng
 * @date: 2022-01-25 12:27
 * @version: v 1.0.0
 */
@Component
public class ExcelListConverter implements Converter<List> {
    @Override
    public Class supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public List convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String stringValue = cellData.getStringValue();
        String[] split = stringValue.split(DictUtils.SEPARATOR);
        List<String> enterpriseList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            enterpriseList.add(split[i]);
        }
        return enterpriseList;
    }

    @Override
    public CellData convertToExcelData(List list, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        list.forEach(item -> {
            String content = item == null ? "" : item.toString();
            stringBuilder.append(content).append(DictUtils.SEPARATOR);
        });
        if (stringBuilder.lastIndexOf(DictUtils.SEPARATOR) != -1) {
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(DictUtils.SEPARATOR));
        }
        return new CellData(stringBuilder.toString());
    }
}
